#pragma once

#define USE_IDISPATCH 1

template<class T>
class CProxyDPanicButtonEvents:
	public ATL::IConnectionPointImpl<T, &__uuidof( DPanicButtonEvents )>
{
public:

	HRESULT Fire_LidStatusChange( bool LidOpen ) {
		HRESULT hr = S_OK;
		T* pThis = static_cast<T*>( this );
		int cConnections = m_vec.GetSize( );

		for ( int iConnection = 0; iConnection < cConnections; iConnection++ ) {
			pThis->Lock( );
				CComPtr<IUnknown> punkConnection = m_vec.GetAt( iConnection );
			pThis->Unlock();

			if ( nullptr == punkConnection ) {
				continue;
			}

#if USE_IDISPATCH
			IDispatch* pConnection = static_cast<IDispatch*>( punkConnection.p );
			if ( pConnection ) {
				CComVariant varParam( LidOpen );
				DISPPARAMS params = { &varParam, nullptr, 1, 0 };
				hr = pConnection->Invoke( 201, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &params, nullptr, nullptr, nullptr );
				debug( L"Fire_LidStatusChange: %d: event dispatch to 0x%08p returned 0x%08x\n", iConnection, pConnection, hr );
			}
#else
			DPanicButtonEvents* pPanicButtonEvents = static_cast<DPanicButtonEvents*>( punkConnection.p );
			if ( pPanicButtonEvents ) {
				pPanicButtonEvents->LidStatusChange( LidOpen );
				debug( L"Fire_LidStatusChange: %d: event dispatched to 0x%08p\n", iConnection, pPanicButtonEvents );
			}
#endif
		}
		return S_OK;
	}

	HRESULT Fire_ButtonStatusChange( bool ButtonPressed ) {
		HRESULT hr = S_OK;
		T* pThis = static_cast<T*>( this );
		int cConnections = m_vec.GetSize( );

		for ( int iConnection = 0; iConnection < cConnections; iConnection++ ) {
			pThis->Lock( );
				CComPtr<IUnknown> punkConnection = m_vec.GetAt( iConnection );
			pThis->Unlock( );

			if ( nullptr == punkConnection ) {
				continue;
			}

#if USE_IDISPATCH
			IDispatch* pConnection = static_cast<IDispatch*>( punkConnection.p );
			if ( pConnection ) {
				CComVariant varParam( ButtonPressed );
				DISPPARAMS params = { &varParam, nullptr, 1, 0 };
				hr = pConnection->Invoke( 202, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &params, nullptr, nullptr, nullptr );
				debug( L"Fire_ButtonStatusChange: %d: event dispatch to 0x%08p returned 0x%08x\n", iConnection, pConnection, hr );
			}
#else
			DPanicButtonEvents* pPanicButtonEvents = static_cast<DPanicButtonEvents*>( punkConnection.p );
			if ( pPanicButtonEvents ) {
				pPanicButtonEvents->ButtonStatusChange( ButtonPressed );
				debug( L"Fire_ButtonStatusChange: %d: event dispatched to 0x%08p\n", iConnection, pPanicButtonEvents );
			}
#endif
		}
		return S_OK;
	}

};
